<template>
  <div class="details-right" v-show="!loading">
    <header class="view-header">
      <!-- 面包屑 -->
      <el-breadcrumb separator="/" v-if="breadList">
        <el-breadcrumb-item v-for="item in breadList" :key="item.id" @click="handleChange(item)">{{
          item.fileName
        }}</el-breadcrumb-item>
      </el-breadcrumb>
      <p class="document-name" v-else>{{ docName }}</p>
      <div class="header-tools">
        <el-tooltip effect="dark" content="返回">
          <el-button @click.stop="handleBack" text>
            <svg class="action-icon" aria-hidden="true" width="18" height="18">
              <use xlink:href="#iconzuojiantou" fill="#409eff" />
            </svg>
          </el-button>
        </el-tooltip>
        <el-tooltip v-if="fileData" effect="dark" content="收藏">
          <el-button @click.stop="handleLike" text>
            <i
              v-if="findUserLike?.is_status === 1"
              style="color: #6f51ff"
              class="iconfont iconshoucang"
            ></i>
            <i v-else class="iconfont iconc-star"></i>
          </el-button>
        </el-tooltip>
        <template v-if="fileData && fileData.type === 'txt'">
          <el-tooltip effect="dark" content="编辑">
            <el-button @click.stop="hanleEditor" text>
              <svg class="action-icon" aria-hidden="true" width="18" height="18">
                <use xlink:href="#iconbianji1" />
              </svg>
            </el-button>
          </el-tooltip>
        </template>
        <template v-if="fileData && fileData.type !== 'folder' && fileData.type !== 'txt'">
          <el-tooltip effect="dark" content="下载">
            <el-button @click.stop="hanleDown" text>
              <svg class="action-icon" aria-hidden="true" width="18" height="18">
                <use xlink:href="#iconwangpan-xiazai1x" />
              </svg>
            </el-button>
          </el-tooltip>
        </template>
      </div>
    </header>

    <div class="view-container">
      <DocView v-if="!fileData"></DocView>
      <RichTextView
        v-if="fileData && fileData.filetype === 'txt'"
        :fileData="fileData"
      ></RichTextView>
      <DocView v-if="fileData && fileData.filetype === 'folder'" :fileData="fileData"> </DocView>
      <FileView
        v-if="fileData && fileType && fileData.filetype !== 'txt' && fileData.filetype !== 'folder'"
        :fileData="fileData"
        :fileType="fileType"
      >
      </FileView>
      <Comment v-if="fileData && fileData.filetype !== 'folder'" :fileData="fileData"></Comment>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, computed, watch } from 'vue'
import Router from '@/router'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

// import { newLikeData, editLikeData } from '@/apis/system/doc-center'
import { editCollectData, newCollectData } from '@/apis/system/docCollect'

import FileView from './FileView.vue'
import Comment from '@/views/documentCenter/components/Comment.vue'
import RichTextView from './RichTextView.vue'
import DocView from './DocView.vue'

import { store } from '@/store/doc-center'
import { storeToRefs } from 'pinia'
import { IfileListData, Ilike } from '../../config/fileListData'

const props = defineProps({
  treeNode: {
    type: Object,
    default: () => {}
  },
  treeItem: {
    type: Object,
    default: () => {}
  },
  breadListArr: {
    type: Object,
    default: () => {}
  }
})
const docStore = store()
const { docListData, loading } = storeToRefs(docStore)

const $router = useRouter()

const fileType = ref<string>()
const fileData = ref<IfileListData>()
const docName = ref<string>()
const fileId = ref<number>()
const parentId = ref<number>()
const is_like = ref<number>(+$router.currentRoute.value.query.is_like!) // 外部收藏点击进来，临时显示

onMounted(() => {
  docName.value = $router.currentRoute.value.query.name as string
  parentId.value = +$router.currentRoute.value.query.parent_id!
  if (!!$router.currentRoute.value.query.file_id) {
    fileId.value = +$router.currentRoute.value.query.file_id!
    breadList.value = props.breadListArr
    _findFIle(docListData.value)
    fileData.value = findData.value
    getLikeData()
    getDataList()
  }
})

/**
 * @desc: 获取面包屑/和左侧点击文件的id
 */
const breadList = ref()
interface IbreadList {
  level: number
  data: IfileListData
  parent: IbreadList
}
watch(
  () => props.treeItem,
  (newVal) => {
    fileId.value = newVal.id
    fileData.value = newVal as IfileListData
    getDataList()
    getLikeData()
  },
  { deep: true }
)

watch(
  () => props.treeNode,
  (newVal) => {
    let arr: object[] = []
    const _findFileName = (item: IbreadList) => {
      if (item.level >= 1) {
        arr.unshift({ fileName: item.data.fileName, id: item.data.id })
        _findFileName(item.parent)
      }
    }
    // 获取面包屑
    _findFileName(newVal as IbreadList)
    breadList.value = arr
  }
)

watch(
  () => props.breadListArr,
  (newVal) => {
    breadList.value = newVal
  }
)

/**
 *
 * @desc:获取登录用户信息
 */
const getUserInfo = computed(() => {
  return JSON.parse(localStorage.getItem('user') as string) || ''
})

/**
 * @desc:刷新页面
 * @return {*}
 */
const emit = defineEmits(['send-refresh', 'send-breadList-node'])
const refresh = (id: number) => {
  emit('send-refresh', id)
}

/**
 * @desc: 获取右侧内容/和对应图标
 *
 */
const getDataList = () => {
  if (fileData.value?.filepath) {
    const arr = fileData.value.filepath.split('.')
    const last = arr[arr.length - 1]
    fileType.value = fileTypeHash[last.toLocaleLowerCase()]
  }
}

const fileTypeHash: { [key: string]: string } = {
  bmp: 'img',
  jpg: 'img',
  png: 'img',
  gif: 'img',
  jpeg: 'img',
  cdr: 'img',
  psd: 'img',
  doc: 'doc',
  docx: 'doc',
  pdf: 'doc',
  ppt: 'doc',
  pptx: 'doc',
  xlsx: 'doc',
  xls: 'doc',
  mp3: 'mp3',
  wav: 'mp3',
  mp4: 'mp4',
  webm: 'mp4',
  ogg: 'mp4'
}

/**
 * @desc: 查找该文件id在，所有文件中对应的数据
 * @return {*}
 */
const findData = ref()
const _findFIle = (item: IfileListData[]) => {
  for (let i = 0; i < item.length; i++) {
    if (item[i].id === fileId.value) {
      findData.value = item[i]
    }
    if (item[i]?.children_file && item[i]?.children_file.length) {
      _findFIle(item[i]?.children_file)
    }
  }
}

/**
 * @desc: 切换面包屑
 */
const handleChange = (item: { id: number }) => {
  emit('send-breadList-node', item.id)
  fileId.value = item.id
  _findFIle(docListData.value)
  fileData.value = findData.value
  for (let i = 0; i < breadList.value.length; i++) {
    if (breadList.value[i].id === item.id) {
      breadList.value = breadList.value.slice(0, i + 1)
      break
    }
  }
}

/**
 * @desc: 返回
 */
const handleBack = () => {
  // 清空store里面的数据
  docListData.value = {} as IfileListData[]
  Router.back()
}

/**
 * @desc: 编辑
 */
const hanleEditor = () => {
  docStore.docRichEditorFile = fileData.value as IfileListData
  $router.push({
    name: 'DocRichEditor',
    query: { id: fileData.value!.id, fileName: fileData.value?.fileName }
  })
}

/**
 * @desc: 获取单条内容是否收藏
 */
const findUserLike = ref<Ilike>()
const getLikeData = () => {
  findUserLike.value = fileData.value?.doc_collect?.find((item: Ilike) => {
    return item.user_id === getUserInfo.value.id
  })
}

/**
 * @desc:收藏
 */
const handleLike = () => {
  // 若没有，新增收藏表/否则，修改status
  if (!!findUserLike.value) {
    findUserLike.value.is_status = findUserLike.value.is_status === 0 ? 1 : 0
    editLike({
      _id: findUserLike.value.id,
      is_status: findUserLike.value.is_status
    })
  } else {
    createNewLike()
  }
}

/**
 * @desc:新增收藏
 */
const createNewLike = () => {
  let params = {
    file_id: fileData.value?.id,
    top_parent_id: parentId.value,
    user_id: getUserInfo.value.id,
    is_status: 1
  }
  newCollectData(params)
    .then((res) => {
      if (!res) return
      ElMessage.success('收藏成功！')
      refresh(res.file_id)
      getLikeData()
    })
    .catch(() => {
      ElMessage('服务器内部错误')
    })
}

/**
 * @desc:修改收藏
 */
const editLike = (data: { _id: number; is_status: number }) => {
  editCollectData(data)
    .then((res) => {
      if (!res) return
      switch (data.is_status) {
        case 1:
          ElMessage.success('收藏成功！')
          break
        case 0:
          ElMessage.error('已取消收藏！')
      }
    })
    .catch(() => {
      ElMessage('服务器内部错误')
    })
}

/**
 * @desc: 下载文件
 */
const hanleDown = () => {
  if (fileData.value?.url) {
    let a: any = document.createElement('a')
    a.href = fileData.value?.url
    a.setAttribute('target', '_blank')
    a.setAttribute('download', fileData.value.fileName)
    a.click()
    // 移除a的引用
    setTimeout(() => {
      a = null
    }, 100)
  }
}
</script>

<style lang="less" scoped>
.details-right {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .view-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;

    .document-name {
      font-weight: 600;
      font-size: 16px;
    }

    .header-tools {
      margin-right: 16px;
      display: flex;
    }
    .el-breadcrumb {
      display: flex;
      cursor: pointer;
      overflow: hidden;
      width: 10px;
      flex-grow: 1;
      width: 10px;
      line-height: 25px;

      :deep(.el-breadcrumb__inner) {
        font-weight: 600;
        font-size: 16px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        &:hover {
          color: #337ecc;
        }
      }
    }
  }
  .view-container {
    flex-grow: 1;
    height: 0;
    flex-shrink: 0;
    overflow-y: auto;
  }
}
</style>
